package com.nine.mymall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nine.common.constant.ProductConstant;
import com.nine.common.utils.PageUtils;
import com.nine.common.utils.Query;
import com.nine.mymall.product.dao.AttrAttrgroupRelationDao;
import com.nine.mymall.product.dao.AttrDao;
import com.nine.mymall.product.dao.AttrGroupDao;
import com.nine.mymall.product.dao.CategoryDao;
import com.nine.mymall.product.entity.AttrAttrgroupRelationEntity;
import com.nine.mymall.product.entity.AttrEntity;
import com.nine.mymall.product.entity.AttrGroupEntity;
import com.nine.mymall.product.entity.CategoryEntity;
import com.nine.mymall.product.service.AttrService;
import com.nine.mymall.product.service.CategoryService;
import com.nine.mymall.product.vo.AttrRespVo;
import com.nine.mymall.product.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        // 1、保存基本数据
        this.save(attrEntity);

        // 只有在 attr_type 是 基本属性：1 的时候，才需要保存分组属性
        // attr.getAttrGroupId() 不能是空，否则会生成对应为空的数据，导致查询列表出现问题
        if (attrEntity.getAttrType().longValue() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null) {
            // 2、保存关联关系
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            // 生成的实际数据库对应的实体的attrId
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationDao.insert(relationEntity);
        }

    }

    @Transactional
    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {

        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();

        // 基本类型：1， 其他：0
        queryWrapper.eq("attr_type", "base".equalsIgnoreCase(attrType) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        if (catelogId.longValue() != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }

        // attr_id, attr_name
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);

        List<AttrEntity> records = page.getRecords();

        List<AttrRespVo> attrRespVos = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);

            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                // 分类名称
                attrRespVo.setCatelogName(categoryEntity.getName());
            }


            if ("base".equalsIgnoreCase(attrType)) {
                QueryWrapper<AttrAttrgroupRelationEntity> aareWrapper = new QueryWrapper<>();
                aareWrapper.eq("attr_id", attrEntity.getAttrId());
                AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(aareWrapper);
                if (relationEntity != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    if (attrGroupEntity != null) {
                        // 分组名称
                        attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }
            return attrRespVo;
        }).collect(Collectors.toList());

        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(attrRespVos);
        return pageUtils;
    }

    // 添加缓存信息
    @Cacheable(value = "attr", key = "'attrinfo:' + #root.args[0]")
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, attrRespVo);


        if (attrEntity.getAttrType().longValue() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 设置分组
            QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("attr_id", attrId);
            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(queryWrapper);
            if (relationEntity != null) {
                attrRespVo.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }


        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        // 完整路径
        attrRespVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        attrRespVo.setCatelogName(categoryEntity.getName());
        return attrRespVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);


        if (attrEntity.getAttrType().longValue() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 修改分组关联
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attr.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());

            // 查询是否有数据
            QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("attr_id", attr.getAttrId());
            Integer count = relationDao.selectCount(queryWrapper);
            if (count > 0) {
                UpdateWrapper<AttrAttrgroupRelationEntity> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("attr_id", attr.getAttrId());
                relationDao.update(relationEntity, updateWrapper);
            } else {
                relationDao.insert(relationEntity);
            }
        }


    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {

        List<AttrEntity> list = new ArrayList<>();

        QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_group_id", attrgroupId);
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(queryWrapper);

        if (relationEntities.size() > 0) {
            List<Long> attrIds = relationEntities.stream().map((attrAttrgroupRelationEntity) -> attrAttrgroupRelationEntity.getAttrId())
                    .collect(Collectors.toList());
            Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
            list = (List<AttrEntity>) attrEntities;
        }

        return list;
    }

    /**
     * 获取属性分组没有关联的其他属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {

        // 分类 ----》  属性分组 ---》 属性

        // 1、当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);

        // 获取分类id
        Long catelogId = attrGroupEntity.getCatelogId();

        // 2、当前分组只能关联别的分组没有引用的属性

        // 当前分类下的分组
        QueryWrapper<AttrGroupEntity> entityQueryWrapper = new QueryWrapper<>();
        entityQueryWrapper.eq("catelog_id", catelogId);
        // 其他分组
        List<AttrGroupEntity> groups = attrGroupDao.selectList(entityQueryWrapper);

        List<Long> attrGroupIds = groups.stream().map(item -> item.getAttrGroupId()).collect(Collectors.toList());

        // 这些分组关联的属性
        QueryWrapper<AttrAttrgroupRelationEntity> relationEntityQueryWrapper = new QueryWrapper<>();
        relationEntityQueryWrapper.in("attr_group_id", attrGroupIds);
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(relationEntityQueryWrapper);

        List<Long> attrIds = relationEntities.stream().map(item -> item.getAttrId()).collect(Collectors.toList());

        // 从当前分类的所有属性中，移除这些属性
        QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<>();
        // 本分类下
        attrEntityQueryWrapper.eq("catelog_id", catelogId);
        attrEntityQueryWrapper.eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if(attrIds != null && attrIds.size() > 0){
            attrEntityQueryWrapper.notIn("attr_id", attrIds);
        }

        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            attrEntityQueryWrapper.and((item) ->{
                item.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> iPage = new Query<AttrEntity>().getPage(params);
        IPage<AttrEntity> page = this.page(iPage, attrEntityQueryWrapper);

        PageUtils pageUtils = new PageUtils(page);

        return pageUtils;
    }

    /**
     * 指定的所有属性里面，检索出需要索引的属性
     * @param attrIds
     * @return
     */
    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {
        return baseMapper.selectSearchAttrs(attrIds);
    }


}